const Router = require("./index")
const {verifyWebAuth,handlePhotos,handleAvater,handleMemory} = require("@/zy-common/middleware")
const {ossPut} = require("@/zy-common/config/oss")
const {send} = require("@/zy-common/utils")

//头像上传
Router.post("/avatar",verifyWebAuth,handleAvater,async (ctx,next) => {
  try {
    const filesArr = ctx.req.files || []
    let data = await uploadsFn(filesArr,'filename','path','avatar')
    send(ctx,200,'200','上传成功',data)
 } catch (error) {
   console.log(error);
 }
})

//图片集上传
Router.post("/upload",handlePhotos,async (ctx,next) => {
  try {

    const filesArr = ctx.req.files || []
    let data = await uploadsFn(filesArr,'filename','path','images')
    send(ctx,200,'200','上传成功',data)
 } catch (error) {
   console.log(error);
 }
})

//内存上传
Router.post("/memory",handleMemory,async (ctx,next) => {
  try {
    const {ossFile} = ctx.req.body || ''
    const filesArr = ctx.req.files || []
    let data = await uploadsFn(filesArr,'originalname','buffer',ossFile)
    send(ctx,200,'200','上传成功',data)
  } catch (error) {
    console.log(error);
  }
})


//utils 
// fileName ctx.req.files 文件名字段
// origin   ctx.req.files 保存保存文件位置字段
const uploadsFn = async (filesArr,fileName,origin,ossFile) => {
  try {
   let res = await Promise.all(filesArr.map(file => ossPut(file[fileName],file[origin],ossFile)))
   return res.map(file => {
     const {name,url} = file;
     const {status,statusMessage} = file.res
     return {name,url,status,statusMessage,}
   })

 } catch (error) {
  console.log(error);
}
}
